package qe.spider.grab;

import cn.hutool.core.io.FileUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Data
public class ParseThsPool {
    //    public static List<String> disks = List.of("D:\\Tools\\THSGeGuData\\", "D:\\Tools\\THSPlateData\\");
    public static List<String> disks = List.of("D:\\Tools\\THSTrade\\Pool\\", "X:\\Tools\\THSTrade\\Pool\\", "Y:\\Tools\\THSTrade\\Pool\\", "Z:\\Tools\\THSTrade\\Pool\\");
    private File excelFile;

    private List<String> lines = new ArrayList<>();
    private List<String> title = new ArrayList<>();
    private List<Integer> titleIdx = new ArrayList<>();
    private List<String> all = new ArrayList<>();

    public ParseThsPool(File excelFile) {
        this.excelFile = excelFile;
    }

    public ParseThsPool(String excelFilePath) {
        this.excelFile = new File(excelFilePath);
    }


    public List<String> parseTitle() {
        this.lines = FileUtil.readLines(excelFile, Charset.forName("gb2312"));
        int i = 0;
        for (String t : lines.get(0).split("\t")) {
            title.add(t.trim());
            titleIdx.add(i);
            i++;
        }
        return title;
    }

    public List<String> parseAllLines() {
        if (title.isEmpty()) parseTitle();
        for (int i = 1; i < this.lines.size(); i++) {
            List<String> sd = new ArrayList<>();
            for (String t : lines.get(i).split("\t")) {
                sd.add(t.trim());
            }
            if (sd.size() == title.size()) {
                String s = parseLineStock(sd);
                all.add(s);
            }
        }
        return all;
    }

    private String parseLineStock(List<String> items) {
        for (int i = 0; i < title.size(); i++) {
            String t = title.get(i);
            String d = items.get(i);//.replaceAll("-", "");
            if (d.isEmpty()) continue;
            try {
                if ("代码".equals(t)) {
                    String code = d.substring(2);
                    return code;
                }
            } catch (Exception e) {
                log.error("解析同花顺数据异常----t:{}----d:{}", t, d);
                e.printStackTrace();
            }
        }
        return "";
    }

    public static void main(String[] args) throws IOException {
        ParseThsPool parser = new ParseThsPool(new File("D:\\Tools\\THSTrade\\Pool\\2024-06-03\\Table.xls"));
        parser.parseTitle();
        parser.parseAllLines();
        log.debug("{}", parser.all);
    }
}
